package com.pc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 指定唤醒：A执行完通知B执行，B执行完通知C执行
 * */
public class C {
    public static void main(String[] args) {
        Data3 data3 = new Data3();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                data3.printA();
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                data3.printB();
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                data3.printC();
            }
        }, "C").start();
    }
}

// 资源类
class Data3 {
    private Lock lock = new ReentrantLock();
    // 精确的通知和唤醒线程
    private Condition condition1 = lock.newCondition();  // condition1 监视线程A
    private Condition condition2 = lock.newCondition();  // condition2 监视线程B
    private Condition condition3 = lock.newCondition();  // condition3 监视线程C

    private int num = 1;   // 1=>A, 2=>B, 3=>C

    public void printA() {
        lock.lock();
        try {
            // 业务代码
            // while==>防止虚假唤醒
            while (num != 1) {
                condition1.await();
            }
            System.out.println(Thread.currentThread().getName() + "=>AAA");
            // 唤醒B
            num = 2;
            condition2.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printB() {
        lock.lock();
        try {
            while (num != 2) {
                // 等待
                condition2.await();
            }
            System.out.println(Thread.currentThread().getName() + "=>BBB");
            // 唤醒C
            num = 3;
            condition3.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printC() {
        lock.lock();
        try {
            while (num != 3) {
                // 等待
                condition3.await();
            }
            System.out.println(Thread.currentThread().getName() + "=>CCC");
            // 唤醒A
            num = 1;
            condition1.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
